Program ret_max_int
      character*6 ticker
      character*8 cusp,cusip
      integer(kind=8):: nshrs,nvalue,jvalue,ivol,numshrs,ntot(5500)
      dimension nep(5500),ntype(5500),jyr(5500),jmn(5500),jdy(5500),vwret(5500),retrn(5500),pctshrt(5500),ishrout(5500)
!      open(unit=10,file='e:\FIS_duration\episode_data_type_total.txt')
!      open(unit=99,file='e:\FIS_duration\rets_to_max_end_short_int.txt')
      open(unit=10,file='e:\FIS_duration\episode_data_type_total_rep.txt')
      open(unit=99,file='e:\FIS_duration\rets_to_max_end_short_int_rep.txt')
      iend=0
      i=0
1     i=i+1      
      read(10,1000,end=900)nep(i),ntype(i),jast,jyr(i),jmn(i),jdy(i),cusp,ticker,itickt,numshrs,age,favg,fmax,fmin,fstd,iperm,price,ivol,retrn(i),ishrout(i),vwret(i),util,nshrs,ntot(i)
1000  format(1x,i4,1x,i1,1x,i8,1x,i4,2i2,1x,a8,2x,a6,4x,i9,1x,i14,5(1x,f11.4),1x,i5,1x,f9.2,1x,i10,1x,f10.6,1x,i9,1x,f9.6,1x,f6.2,1x,i13,1x,i12) 
      pctshrt(i)=float(ntot(i))/(1000.*float(ishrout(i)))
      if(nep(i).eq.nep(1)) go to 1
5     icnt=i-1
      icntm=icnt-1
      if(icnt.le.10) go to 100
      pctbeg=-9.9
      pctmax=-9.9
      pctend=-9.9
      nshrt=0
      nbg=0
      nmax=0
      nend=0
      nshrt=0
      do 10 n=1,icntm
          if(pctshrt(n).le.0) go to 10
          nshrt=nshrt+1
          if(nshrt.eq.1) pctbeg=pctshrt(n)
          if(nshrt.eq.1) nbg=n
          pctend=pctshrt(n)
          nend=n
          if(pctshrt(n).gt.pctmax) nmax=n
          if(pctshrt(n).gt.pctmax) pctmax=pctshrt(n)
10    continue   
      if(nshrt.le.1) go to 100
      if(nmax.eq.1) go to 30
      ibg=nbg+1
      ret2max=1.
      xs2max=1.
      do 20 ii=ibg,nmax
          ret2max=ret2max*(1.+retrn(ii))
20    xs2max=xs2max*(1.+retrn(ii)-vwret(ii))
      ret2max=ret2max-1.
      xs2max=xs2max-1.
30    continue
      if(nmax.eq.nend) go to 50
      ibg=nmax+1
      ret2end=1.
      xs2end=1.
      do 40 ii=ibg,nend
          ret2end=ret2end*(1.+retrn(ii))
          xs2end=xs2end*(1.+retrn(ii)-vwret(ii))
40    continue
50    continue      
      ret2end=ret2end-1.
      xs2end=xs2end-1.
      if(nmax.eq.1) ret2max=-9.9
      if(nmax.eq.1) xs2max=-9.9
      if(nmax.eq.nend) ret2end=-9.9
      if(nmax.eq.nend) xs2end=-9.9
      write(6,9900)nep(1),ntype(1),ret2max,ret2end,xs2max,xs2end,pctbeg,pctmax,pctend,nshrt
      write(99,9900)nep(1),ntype(1),ret2max,ret2end,xs2max,xs2end,pctbeg,pctmax,pctend,nshrt
9900  format(1x,i4,1x,i1,4(1x,f9.6),3(1x,f8.5),1x,i3)      
          
100   continue
      nep(1)=nep(i)
      ntype(1)=ntype(i)
      jyr(1)=jyr(i)
      jmn(1)=jmn(i)
      jdy(1)=jdy(i)
      retrn(1)=retrn(i)
      vwret(1)=vwret(i)
      ntot(1)=ntot(i)
      ishrout(1)=ishrout(i)
      pctshrt(1)=pctshrt(i)
      i=1
      go to 1
900   continue
      iend=iend+1
      if(iend.eq.1) go to 5
      stop
end program ret_max_int